<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="名称" prop="materialParam">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
       <el-form-item label="编号" prop="barCode">
      <el-input v-model="queryParams.serialNo" placeholder="请输入编号" clearable size="small"
        @keyup.enter.native="handleQuery" />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-form-item>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" style="margin-left: 0.55rem;">
       <span><strong>本月发生总额：</strong>{{allMonthAmount}}</span>
      </el-col>
   <el-col :span="1.5" style="margin-left: 6.25rem;">
    <span><strong>当前总余额：</strong>{{allCurrentAmount}}</span>
   </el-col>


    </el-row>

    <el-table v-loading="loading" max-height="620px" :data="accountList" @selection-change="handleSelectionChange"
    :summary-method="getSummaries"
       show-summary

    >
      <el-table-column type="selection" width="65" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="编号" align="center" prop="serialNo" />
      <el-table-column label="期初金额" align="center" prop="initialAmount" />
      <el-table-column label="本月发生额" align="center" prop="thisMonthAmount" />
      <el-table-column label="当前余额" align="center" prop="currentAmount" />
  <el-table-column label="账户流水" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
              @click="dofindDetailByTypeAndaccountId(scope.row.id,scope.row.name,scope.row.initialAmount)"
          >流水</el-button>
</template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 50, 100, 200,500, 1000,2000]"
      @pagination="getList"
    />

<el-dialog title="查看账户流水" :visible.sync="liushuiVisible" width="1250px" style="min-height: 400px;">
    <el-form :model="queryLiushuiParams" ref="queryLiushuiForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="billNo">
        <el-input v-model="queryLiushuiParams.billNo" placeholder="请输入单据编号" clearable size="small"   @keyup.enter.native="handleQueryLiushui"/>
      </el-form-item>
      <el-form-item label="类型" prop="type" >
        <el-select v-model="queryLiushuiParams.type" style="width: 180px;">
          <el-option key="销售出库" label="销售出库" value="销售出库"></el-option>
          <el-option key="采购入库" label="采购入库" value="采购入库"></el-option>
          <el-option key="转账" label="转账" value="转账"></el-option>
          <el-option key="收款" label="收款" value="收款"></el-option>
          <el-option key="付款" label="付款" value="付款"></el-option>
          <el-option key="支出" label="支出" value="支出"></el-option>
        </el-select>
        <!-- <el-input v-model="queryLiushuiParams.type" placeholder="请输入单据编号" clearable size="small"   @keyup.enter.native="handleQueryLiushui"/> -->
      </el-form-item>
      <el-form-item label="单据日期" prop="operTimeRange">
      <el-date-picker size="small"
            v-model="queryLiushuiParams.operTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 330px;">
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryLiushui">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQueryLiushui">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExportLiushui">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="liushuiList"  style="min-height: 400px;" show-summary :summary-method="getSummaries1">
          <el-table-column type="selection" width="65" align="center" />
          <el-table-column label="单据编号" align="center" prop="number" >
             <template slot-scope="scope">
             <el-link type="primary" @click="myHandleDetail(scope.row)">{{scope.row.number}}</el-link>
               </template>
               </el-table-column>
          <el-table-column label="类型" align="center" prop="type" />
          <el-table-column label="单位信息" align="center" prop="supplierName" />
          <el-table-column label="金额" align="center" prop="changeAmount" />
          <el-table-column label="余额" align="center" prop="balance" />
      <el-table-column label="单据日期" align="center" prop="operTime" />
    </el-table>
    <pagination
          v-show="liushuitotal>0"
          :total="liushuitotal"
          :page.sync="queryLiushuiParams.pageNum"
          :limit.sync="queryLiushuiParams.pageSize"
          :page-sizes="[10, 50, 100, 200,500, 1000,2000]"
          @pagination="handleQueryLiushui()"
        />
  </el-dialog>
   <bill-detail ref="billDetail"></bill-detail>
   <financial-detail ref="financialDetail"></financial-detail>
  </div>
</template>

<script>
import { reportaccountlist,getAccountStatistics,findAccountInOutList } from "@/api/basicsystem/account";
import BillDetail from '../comm/dialog/BillDetail'
import FinancialDetail from '../../basicsystem/comm/dialog/BillDetail'
// import FinancialDetail from '../comm/dialog/FinancialDetail'
import { findBillDetailByNumber } from "@/api/bill/retail";
import { getAccountDetailByNumber } from "@/api/basicsystem/accounthead";

import * as math from 'mathjs'
    export default {
  name: "accountreport",
  components: {
    BillDetail,
    FinancialDetail
  },
  data() {
    return {

   liushuiVisible:false,//流水
   liushuiList:[],//流水集合
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      liushuitotal:0,
      total: 0,
     // 结算账号表格数据
     accountList: [],
     // 弹出层标题
     title: "",
     // 是否显示弹出层
     open: false,
     // 查询流水参数
     queryLiushuiParams:{
       operTimeRange:null,
       pageNum: 1,
       pageSize: 10,
       billNo:null,
       operTimeBegin:null,
       operTimeEnd:null,
       type:null,
     },
     // 查询参数
     queryParams: {
       pageNum: 1,
       pageSize: 10,
       name: null,
       serialNo: null,
       initialAmount: null,
       currentAmount: null,
       isDefault: null,
       tenantId: null,
       deleteFlag: null
     },
    allMonthAmount: '',
    allCurrentAmount: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      }
    };
  },
  created() {
    this.getList();

  },
  methods: {
    getSummaries1(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '';
                return;
              }
              if (index === 1) {
                sums[index] = '合计';
                return;
              }
              if (index === 2) {
                sums[index] = '';
                return;
              }
              if (index === 3) {
                sums[index] = '';
                return;
              }
              if (index === 5) {
                sums[index] = '';
                return;
              }
              if (index === 6) {
                sums[index] = '';
                return;
              }
              const values = data.map(item => Number(item[column.property]));
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                      return math.add(math.bignumber(prev),math.bignumber(curr));
                  } else {
                      return math.bignumber(prev);
                  }
                }, 0);
                sums[index] += '';//可以写单位
              } else {
                sums[index] = 'N/A';
              }
            });
            return sums;
          },
    /** 账户流水页面重置按钮操作 */
    resetQueryLiushui() {
      this.resetForm("queryLiushuiForm");
      this.queryLiushuiParams.pageNum=1 ;
      this.queryLiushuiParams.pageSize =10;
      this.handleQueryLiushui();
    },
     /** 账户流水查询按钮操作 */
    handleQueryLiushui(){
      this.findAccountInOutList();
    },
    //根据单据查询详情
    myHandleDetail(row){
        let that = this
        //this.toFromType = row.fromType;
        if(row.fromType === 'bill') {
           let queryParm={ number: row.number }
           findBillDetailByNumber(queryParm).then(response => {
             //this.liushuiList = response.data;
             that.$refs.billDetail.show(response.data,row.type);
             that.$refs.billDetail.title=response.data.subType+""+response.data.type+"-详情";
           });
        }else if(row.fromType === 'financial') {
            console.log(row)
            getAccountDetailByNumber({ billNo: row.number }).then((res) => {
              console.log(res)
              if (res && res.code === 200) {
                that.$refs.financialDetail.show(res.data, row.type);
                that.$refs.financialDetail.title="详情";
              }
            })
        }
    },
    //根据Id查询流水
        dofindDetailByTypeAndaccountId(accountId,accountName,initialAmount){
             this.liushuiVisible=true;
             this.queryLiushuiParams.pageNum=1 ;
             this.queryLiushuiParams.pageSize =10;
             this.queryLiushuiParams.accountId=accountId;
              this.queryLiushuiParams.accountName =accountName;
             this.queryLiushuiParams.initialAmount=initialAmount;
          this.findAccountInOutList();
        },
        findAccountInOutList(){
          if(this.queryLiushuiParams.operTimeRange !=null){
            this.queryLiushuiParams.operTimeBegin = this.parseTime(this.queryLiushuiParams.operTimeRange[0],'{y}-{m}-{d} {h}:{i}:{s}')
            this.queryLiushuiParams.operTimeEnd = this.parseTime(this.queryLiushuiParams.operTimeRange[1],'{y}-{m}-{d} {h}:{i}:{s}')
          }else{
            this.queryLiushuiParams.operTimeBegin = null
            this.queryLiushuiParams.operTimeEnd = null
          }
           findAccountInOutList(this.queryLiushuiParams).then(response => {
             this.liushuiList = response.data;
             this.liushuitotal = response.total;
           });
        },
    getSummaries(param) {
               const { columns, data } = param;
               const sums = [];
               columns.forEach((column, index) => {
                 if (index === 0) {
                   sums[index] = '合计';
                   return;
                 }
                 if (index === 1) {
                   sums[index] = '-';
                   return;
                 }
                if (index === 2) {
                   sums[index] = '-';
                   return;
                 }
                 if (index === 6) {
                   sums[index] = '';
                   return;
                 }
                 const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                  sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                     if (!isNaN(value)) {
                       return math.add(math.bignumber(prev),math.bignumber(curr));
                     } else {
                       return math.bignumber(prev);
                     }
                  }, 0);
                  sums[index] += '';//可以写单位
                }
               });
               return sums;
             },

    /** 查询类型下拉树结构 */
    materialcategorytreeselect() {
      materialcategorytreeselect().then(response => {
        this.materialcategoryOptions = response.data;
      });
    },
    /** 查询库存列表 */
    getList() {
     this.loading = true;
     reportaccountlist(this.queryParams).then(response => {
       this.accountList = response.rows;
       this.total = response.total;
       this.loading = false;
     });
      this.getAccountStatistics()
    },
    /** 查询统计数据 */
    getAccountStatistics() {
     this.loading = true;
     getAccountStatistics(this.queryParams).then(response => {
       if(response.data){
         this.allMonthAmount = response.data.allMonthAmount;
         this.allCurrentAmount = response.data.allCurrentAmount;
          this.loading = false;
       }
     });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      // this.getAccountStatistics();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMaterialunit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改计量单位";
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('/basicsystem/account/reportExport', {
        ...this.queryParams
      }, `账户统计_${this.parseTime(new Date(),'{y}-{m}-{d}')}.xlsx`)
    },
    /** 导出流水按钮操作 */
    handleExportLiushui(){
      this.download('/basicsystem/account/exportAccountInOutList', {
        ...this.queryLiushuiParams
      }, `${this.queryLiushuiParams.accountName}_账户流水_${this.parseTime(new Date(),'{y}-{m}-{d}')}.xlsx`)
    }
  }
};
</script>
